//
//  FWCOAuthViewController.swift
//  微博项目001
//
//  Created by 樊武超 on 16/4/11.
//  Copyright © 2016年 樊武超. All rights reserved.
//

import UIKit
import SVProgressHUD

class FWCOAuthViewController: UIViewController,UIWebViewDelegate {
    let webView=UIWebView()
    
    
    
    
    
    override func loadView(){
        view=webView
        webView.delegate = self
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor=UIColor(red: 237.0/255, green: 237.0/255, blue: 237.0/255, alpha: 1)
         navigationItem.leftBarButtonItem=UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "dianjiguanbi")
        navigationItem.rightBarButtonItem=UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "dianjilezidongtianchong")
        
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        let request=NSURLRequest(URL: url!)
        webView.loadRequest(request)
        
    }
    func dianjiguanbi(){
    
        self.dismissViewControllerAnimated(true, completion: nil)
        SVProgressHUD.dismiss()
    }
    func dianjilezidongtianchong(){
 webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '15221514992', document.getElementById('passwd').value = 'fwc19900328'")
     }
    func webViewDidStartLoad(webView: UIWebView) {
         SVProgressHUD.show()
     }
    func webViewDidFinishLoad(webView: UIWebView) {
        let webTitle=webView.stringByEvaluatingJavaScriptFromString("document.title")
        self.title=webTitle
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString=request.URL?.absoluteString ?? ""
        let flag="code="
        if urlString.containsString(flag) {
            let range=urlString.rangeOfString(flag)
            let code=urlString.substringFromIndex((range?.endIndex)!)
            print(code)
            
            FWCHomeViewModel.shareHomeViewModel.loadViewController(code, finshed: { (issuccess) -> () in
                
                if !issuccess {
                    
                    SVProgressHUD.showErrorWithStatus("加载失败")
                      return
                }
                UIApplication.sharedApplication().keyWindow?.rootViewController=FWCWelcomeViewController()
                
                
            })
            
            
            return false
            
            
        }
        return true
    }
    
}
